<template>
	<view class="container">
		<!-- 显示选中的图片 -->
		<image :src="selectedImg" class="img" v-if="selectedImg" />
		<!-- 选择图片按钮 -->
		<button @click="chooseImage">选择本机图片</button>
		<view class="weather-box" v-if="tomorrowWeather">
			<view>明天日期：{{ tomorrowWeather.date }}</view>
			<view>星期：{{ tomorrowWeather.week }}</view>
			<view>最高温：{{ tomorrowWeather.high }}</view>
			<view>最低温：{{ tomorrowWeather.low }}</view>
		</view>
		<button @click="getTomorrowWeather">获取明天天气预报</button>
		<image :src="downloadedImg" class="img" v-if="downloadedImg" />
		<button @click="downloadNetImage">下载网络图片</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				selectedImg: '/static/logo.png',
				tomorrowWeather: null,
				downloadedImg: ''
			}
		},
		methods: {
			chooseImage() {
				// 调用uni.chooseImage选择图片
				uni.chooseImage({
					count: 1, // 只选1张图片
					sizeType: ['original', 'compressed'], // 允许原图和压缩图
					sourceType: ['album', 'camera'], // 允许从相册和相机选择
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						// 调用uni.previewImage预览图片
						uni.previewImage({
							urls: [tempFilePath], // 预览的图片路径数组
							current: 0, // 当前显示图片的索引
							success: () => {
								console.log('图片预览成功')
							}
						})
						// 将图片显示到界面
						this.selectedImg = tempFilePath
					}
				})
			},
			getTomorrowWeather() {
				uni.request({
					url: 'http://t.weather.sojson.com/api/weather/city/101230501',
					method: 'GET',
					success: (res) => {
						// 接口返回数据中，forecast[1]为明天的预报
						const forecastList = res.data.data.forecast
						if (forecastList && forecastList.length > 1) {
							this.tomorrowWeather = {
								date: forecastList[1].ymd, // 日期
								week: forecastList[1].week, // 星期
								high: forecastList[1].high, // 最高温
								low: forecastList[1].low // 最低温
							}
							console.log('明天天气获取成功：', this.tomorrowWeather)
						} else {
							console.log('未获取到明天的天气数据')
						}
					},
					fail: (err) => {
						console.log('天气请求失败：', err)
					}
				})
			},
			downloadNetImage() {
				const imgUrl = 'https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg'
				uni.downloadFile({
					url: imgUrl,
					// 监听下载进度
					onProgressUpdate: (progress) => {
						console.log(`下载进度：${progress.progress}%`) // 打印进度log
						console.log(`已下载大小：${progress.totalBytesWritten}字节`)
						console.log(`总大小：${progress.totalBytesExpectedToWrite}字节`)
					},
					success: (res) => {
						// 下载成功后显示图片
						if (res.statusCode === 200) {
							this.downloadedImg = res.tempFilePath
							console.log('图片下载成功，临时路径：', res.tempFilePath)
						}
					},
					fail: (err) => {
						console.log('图片下载失败：', err)
					}
				})
			}
		}
	}
</script>

<style>
	.container {
		padding: 20rpx;
		text-align: center;
	}

	.img {
		width: 300rpx;
		height: 300rpx;
		margin: 30rpx 0;
		border: 1px solid #eee;
	}

	button {
		margin: 10rpx 0;
	}
</style>